package com.open.system.controller;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.util.*;

import com.aliyun.oss.OSSClient;
import com.open.common.utils.ShiroUtils;
import com.open.loan.config.OSS.AliyunOSS;
import com.open.loan.domain.req.ReqUploadInfoModel;
import com.open.loan.utils.AliyunOSSUtil;
import com.open.loan.utils.OSSClientUtil;
import com.open.system.domain.LoanFileDO;
import com.open.system.service.LoanFileService;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.codehaus.groovy.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import com.open.system.domain.LoanProductDO;
import com.open.system.service.LoanAdminLogService;
import com.open.system.service.LoanApplyLogService;
import com.open.system.service.LoanProductService;
import com.open.common.controller.BaseController;
import com.open.common.utils.PageUtils;
import com.open.common.utils.Query;
import com.open.common.utils.R;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import sun.misc.BASE64Decoder;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 */

@Controller
@RequestMapping("/system/loanProduct")
public class LoanProductController extends BaseController {
    @Autowired
    private LoanProductService loanProductService;

    @Autowired
    private LoanApplyLogService loanApplyLogService;

    @Autowired
    private LoanAdminLogService loanAdminLogService;

    @Autowired
    private LoanFileService loanFileService;

    @GetMapping()
    @RequiresPermissions("system:loanProduct:loanProduct")
    String LoanProduct() {
        return "system/loanProduct/loanProduct";
    }
    
    @GetMapping("/check")
    @RequiresPermissions("system:loanProduct:loanProduct")
    String LoanProductCheck() {
        return "system/loanProduct/loanProductCheck";
    }

    @ResponseBody
    @GetMapping("/list")
    @RequiresPermissions("system:loanProduct:loanProduct")
    public PageUtils list(@RequestParam Map<String, Object> params) {

        //--操作日志--开始--
        String shopId = getUser().getEmail();
        String adminName = getUser().getName();
        String Module = "借贷产品";
        String detail = "查看了借贷产品列表";
        loanAdminLogService.saveLog(shopId, adminName, Module, detail);
        //--操作日志--结束--
        //查询列表数据
        if(shopId!=null && shopId!="" && !"1".equals(shopId)){
			params.put("remark2",shopId);
		}
        Query query = new Query(params);
        /*if (ShiroUtils.getUserId() != 1) {
            query.put("userId", ShiroUtils.getUserId());
        }*/
        List<LoanProductDO> loanProductList = loanProductService.list(query);
        int total = loanProductService.count(query);
        PageUtils pageUtils = new PageUtils(loanProductList, total);
        return pageUtils;
    }
    
    
    @ResponseBody
    @GetMapping("/listCheck")
    @RequiresPermissions("system:loanProduct:loanProduct")
    public PageUtils listCheck(@RequestParam Map<String, Object> params) {

        //--操作日志--开始--
        String shopId = getUser().getEmail();
        String adminName = getUser().getName();
        String Module = "借贷产品";
        String detail = "查看了借贷产品列表";
        loanAdminLogService.saveLog(shopId, adminName, Module, detail);
        //--操作日志--结束--
      //查询列表数据
        if(shopId!=null && shopId!="" && !"1".equals(shopId)){
			params.put("remark2",shopId);
		}
        //查询列表数据
        Query query = new Query(params);
        List<LoanProductDO> loanProductList = loanProductService.listCheck(query);
        int total = loanProductService.countCheck(query);
        PageUtils pageUtils = new PageUtils(loanProductList, total);
        return pageUtils;
    }

    @GetMapping("/add")
    @RequiresPermissions("system:loanProduct:add")
    String add() {
        return "system/loanProduct/add";
    }

    @GetMapping("/edit/{id}")
    @RequiresPermissions("system:loanProduct:edit")
    String edit(@PathVariable("id") Long id, Model model) {
        LoanProductDO loanProduct = loanProductService.get(id);
        model.addAttribute("loanProduct", loanProduct);
        return "system/loanProduct/edit";
    }

    @GetMapping("/upload/{id}")
    @RequiresPermissions("system:loanProduct:edit")
    String upload(@PathVariable("id") Long id, Model model) {
        LoanProductDO loanProduct = loanProductService.get(id);
        model.addAttribute("loanProduct", loanProduct);
        return "system/loanProduct/upload";
    }

    @GetMapping("/editContract/{id}")
    @RequiresPermissions("system:loanProduct:edit")
    String editcontract(@PathVariable("id") Long id, Model model) {
        LoanProductDO loanProduct = loanProductService.get(id);
        model.addAttribute("loanProduct", loanProduct);
        return "system/loanProduct/editContract";
    }

    /**
     * 保存
     */
    @ResponseBody
    @PostMapping("/save")
    @RequiresPermissions("system:loanProduct:add")
    public R save(LoanProductDO loanProduct) {
        loanProduct.setCreateTime(new Date());
        loanProduct.setUserId(ShiroUtils.getUserId());
        String shopId = getUser().getEmail();
        loanProduct.setRemark2(shopId);
        if (loanProductService.save(loanProduct) > 0) {
            //--操作日志--开始--
            String adminName = getUser().getName();
            String Module = "借贷产品";
            String detail = "新增了借贷产品【" + loanProduct.getProductName() + "】";
            loanAdminLogService.saveLog(shopId, adminName, Module, detail);
            //--操作日志--结束--
            return R.ok();
        }
        return R.error();
    }

    /**
     * 修改
     */
    @ResponseBody
    @RequestMapping("/update")
    @RequiresPermissions("system:loanProduct:edit")
    public R update(LoanProductDO loanProduct) {
    	if(StringUtils.isNotEmpty(loanProduct.getContract())){
    		if(StringUtils.isNotEmpty(loanProduct.getRemark1())){
    			
    		}else {
    			loanProduct.setRemark1("0");
			}
    	}
    	
        loanProductService.update(loanProduct);
        //--操作日志--开始--
        String shopId = getUser().getEmail();
        String adminName = getUser().getName();
        String Module = "借贷产品";
        String detail = "新增了借贷产品【" + loanProduct.getProductName() + "】";
        loanAdminLogService.saveLog(shopId, adminName, Module, detail);
        //--操作日志--结束--
        return R.ok();
    }

    @RequestMapping(value = "/upload1", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> saveUploadFile(HttpServletRequest request) {
        Map<String, Object> output = new HashMap<String, Object>();
        try {
            String base64Images = request.getParameter("base64Data");
            String endpoint = AliyunOSS.endpoint;
            String accessKeyId = AliyunOSS.accessKeyId;
            String accessKeySecret = AliyunOSS.accessKeySecret;
            String bucketName = AliyunOSS.bucketName;
            OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
            String fileName = UUID.randomUUID().toString() + ".png";
            BASE64Decoder decoder = new BASE64Decoder();
            String[] baseStrs = base64Images.split(",");
            byte[] bytes = new byte[0];
            bytes = decoder.decodeBuffer(baseStrs[1]);
            for (int i = 0; i < bytes.length; ++i) {
                if (bytes[i] < 0) {
                    bytes[i] += 256;
                }
            }

            ByteArrayInputStream stream = new ByteArrayInputStream(bytes);
            ossClient.putObject(bucketName, fileName, stream);
            final long duration = 1000L * 60L * 60L * 24L * 365L * 100L;
            long time = System.currentTimeMillis() + duration;
            Date expiration = new Date(time);
            URL url = ossClient.generatePresignedUrl(bucketName, fileName, expiration);

            System.out.println(url);
            output.put("url",url);
            output.put("success",true);

            ossClient.shutdown();
        } catch (IOException e) {
            output.put("success",false);
            e.printStackTrace();
        }

        return output;
    }


    /**
     * 文件上传
     *
     * @param request
     */
    @ResponseBody
    @RequestMapping(value = "/upload")
    @RequiresPermissions("system:loanProduct:edit")
    public R upload(HttpServletRequest request) {

        List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("file");
        MultipartFile file;
        String uploadUrl = "";

        for (int i = 0; i < files.size(); ++i) {
            file = files.get(i);
            try {
                if (null != file) {
                    String filename = file.getOriginalFilename();
                    if (!"".equals(filename.trim())) {
                        OSSClientUtil.init();
                        String name = OSSClientUtil.uploadImg2Oss(file);
                        uploadUrl = OSSClientUtil.getImgUrl(name);

                        LoanFileDO loanFileDO = new LoanFileDO();
                        if (StringUtils.isNotEmpty(request.getParameter("id"))) {
                            loanFileDO.setUserId(Long.parseLong(request.getParameter("id")));
                        }
                        loanFileDO.setRealName(request.getParameter("product_name"));
                        loanFileDO.setFileName(filename);
                        loanFileDO.setFileUrl(uploadUrl);
                        loanFileDO.setCreateTime(new Date());
                        loanFileDO.setExpiredTime(new Date(new Date().getTime() + 3600l * 1000 * 24 * 365 * 10));
                        loanFileDO.setBucketName(AliyunOSS.bucketName);
                        loanFileDO.setEndpoint(AliyunOSS.endpoint);
                        loanFileDO.setRemark1("3");//合同
                        loanFileService.save(loanFileDO);
                    }
                }
            } catch (Exception ex) {
                ex.printStackTrace();
                return R.error();
            }
        }
        HashMap hs = new HashMap();
        hs.put("url", uploadUrl);
        return R.ok(hs);
    }

    /**
     * 删除
     */
    @PostMapping("/remove")
    @ResponseBody
    @RequiresPermissions("system:loanProduct:remove")
    public R remove(Long id) {
        if (loanProductService.remove(id) > 0) {
            //--操作日志--开始--
            String shopId = getUser().getEmail();
            String adminName = getUser().getName();
            String Module = "借贷产品";
            String detail = "新增了借贷产品【" + id + "】";
            loanAdminLogService.saveLog(shopId, adminName, Module, detail);
            //--操作日志--结束--
            return R.ok();
        }
        return R.error();
    }
    
    
    @PostMapping("/pass")
    @ResponseBody
    @RequiresPermissions("system:loanProduct:remove")
    public R pass(Long id) {
    	LoanProductDO productDO=loanProductService.get(id);
    	if(productDO==null){
    		 return R.error();
    	}
    	productDO.setRemark1("1");
        if (loanProductService.update(productDO) > 0) {
            //--操作日志--开始--
            String shopId = getUser().getEmail();
            String adminName = getUser().getName();
            String Module = "借贷产品";
            String detail = "审核通过了借贷产品合同【" + id + "】";
            loanAdminLogService.saveLog(shopId, adminName, Module, detail);
            //--操作日志--结束--
            return R.ok();
        }
        return R.error();
    }
    
    
    @PostMapping("/nopass")
    @ResponseBody
    @RequiresPermissions("system:loanProduct:remove")
    public R nopass(Long id) {
    	LoanProductDO productDO=loanProductService.get(id);
    	if(productDO==null){
    		 return R.error();
    	}
    	productDO.setRemark1("2");
        if (loanProductService.update(productDO) > 0) {
            //--操作日志--开始--
            String shopId = getUser().getEmail();
            String adminName = getUser().getName();
            String Module = "借贷产品";
            String detail = "驳回了借贷产品合同【" + id + "】";
            loanAdminLogService.saveLog(shopId, adminName, Module, detail);
            //--操作日志--结束--
            return R.ok();
        }
        return R.error();
    }
    

    /**
     * 删除
     */
    @PostMapping("/batchRemove")
    @ResponseBody
    @RequiresPermissions("system:loanProduct:batchRemove")
    public R remove(@RequestParam("ids[]") Long[] ids) {
        loanProductService.batchRemove(ids);
        return R.ok();
    }

}
